package com.shou.auth.controller;

import com.shou.auth.model.User;
import com.shou.auth.service.UserService;
import com.shou.auth.util.JwtUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.*;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api")
public class AuthController {

    @Autowired
    private final AuthenticationManager authenticationManager;
    @Autowired
    private final UserService userService;
    @Autowired
    private final JwtUtil jwtUtil;

    public AuthController(AuthenticationManager authenticationManager, UserService userService, JwtUtil jwtUtil) {
        this.authenticationManager = authenticationManager;
        this.userService = userService;
        this.jwtUtil = jwtUtil;
    }

    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody Map<String, String> request) {
        String loginName = request.get("loginName");  // 使用 loginName 代替 username
        String password = request.get("password");

        // 修正方法名 findByUsername -> findByLoginName
        if (userService.findByLoginName(loginName).isPresent()) {
            return ResponseEntity.badRequest().body("用户已存在");
        }

        User newUser = userService.registerUser(loginName, password);
        return ResponseEntity.ok(Map.of("message", "注册成功", "userId", newUser.getUserId()));
    }

     @PostMapping("/login")
     public ResponseEntity<?> login(@RequestBody Map<String, String> request) {
         String loginName = request.get("loginName");
         String password = request.get("password");

         if (loginName == null || password == null || loginName.isBlank() || password.isBlank()) {
             return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                     .body(Map.of("error", "用户名和密码不能为空"));
         }

         try {
             authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginName, password));
             UserDetails userDetails = userService.loadUserByUsername(loginName);
             String token = jwtUtil.generateToken(userDetails);

             return ResponseEntity.ok(Map.of("token", token));
         } catch (BadCredentialsException e) {
             return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                     .body(Map.of("error", "用户名或密码错误"));
         } catch (DisabledException e) {
             return ResponseEntity.status(HttpStatus.FORBIDDEN)
                     .body(Map.of("error", "账户已被禁用"));
         } catch (LockedException e) {
             return ResponseEntity.status(HttpStatus.FORBIDDEN)
                     .body(Map.of("error", "账户已被锁定"));
         }
     }
}
